<?php

namespace App\Http\Requests\UserCenter;

use Illuminate\Foundation\Http\FormRequest;
use Validator;
use Hash;
use Auth;
use Illuminate\Http\Exceptions\HttpResponseException;


class ChangePasswordRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * 添加自定义验证规则
     *
     * @return bool
     */
    public function addValidator()
    {
        //验证原密码是否正确
        Validator::extend('check_password', function ($attribute, $value, $parameters, $validator) {
            return Hash::check($value,Auth::user()->password);
        });

    }

    /**
     * Get the validation rules that apply to the request.
     * 获取适用于请求的验证规则。
     *
     * @return array
     */
    public function rules()
    {
        $this->addValidator();
        return [
            //required 表单是否填写  |confirmed xx字段与xx_confirmation字段是否一致
            'original_password' => 'sometimes|required|check_password',
            'password' => 'sometimes|required|confirmed|alpha_dash|between:8,16',
            'password_confirmation' => 'sometimes|required',
        ];
    }

    /**
     * 获取已定义的验证规则的错误消息。
     *
     * @return array
     */
    public function messages()
    {
        return [
            'original_password.required'  => '原密码不能为空',
            'original_password.check_password'  => '原密码错误',

            'password.required' => '密码不能为空',
            'password.confirmed' => '再次密码不一致',
            'password.alpha_dash' => '密码仅可用 字母 数字 破折号(-) 以及 下线线(_) 构成',
            'password.between' => '密码长度必须在8-16之间',

            'password_confirmation.required'  => '确认密码不能为空',
        ];
    }


    public function failedValidation(\Illuminate\Contracts\Validation\Validator $validator)
    {
        throw (new HttpResponseException(response()->json([
            'status_code' => 500,
            'error' => $validator->errors()->all(),
        ], 200)));
    }
}
